﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace DataPersistence
{
    public class QueryData
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        Database db = new Database();

        /// <summary>
        /// 获取数据库名称
        /// </summary>
        /// <param name="DBName">数据库名称</param>
        /// <returns></returns>
        public DataSet GetDatabasesName(string DBName)
        {
            DataSet ds = new DataSet();
            try
            {
                SqlCommand scomm = new SqlCommand()
                {
                    CommandText = "select name From master.dbo.sysdatabases where status<>512 AND (name LIKE 'ERP%' or name LIKE 'KIS%')"
                };

                db.dataAdapter(scomm, DBName).Fill(ds);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw;
            }
            return ds;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="scomm">SqlCommand实例</param>
        /// <param name="DBName">数据库名称</param>
        /// <returns></returns>
        public JArray GetData(SqlCommand scomm, string DBName)
        {
            DataSet ds = new DataSet();
            JArray jaResult = new JArray();
            try
            {
                db.dataAdapter(scomm, DBName).Fill(ds);
                string result = JsonConvert.SerializeObject(ds);
                JObject joResult = JObject.Parse(result);
                jaResult = (JArray)joResult["Table"];
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw;
            }
            return jaResult;
        }
    }
}
